﻿using Microsoft.Owin.Hosting;
using Serilog;
using Sustainalytics.ActiveMQHelper;
using Sustainalytics.ESGComputing.Service.Infrastructure;
using System;
using System.Configuration.Abstractions;

namespace Sustainalytics.ESGComputing.Service
{
    internal static class ProgramConsole
    {
        private static ESGDataSource esgDS = ESGDataSource.GetInstance();

        private static ActiveMQQueueConsumer consumer;

        static ProgramConsole()
        {
            AppDomain.CurrentDomain.ProcessExit += ProcessExitHandler;
        }

        private static void ProcessExitHandler(object sender, EventArgs e)
        {
            consumer.Dispose();
            esgDS = null;
        }

        public static void Start()
        {
            try
            {
                var url = HostConfig.GetHostUrl();
                using (WebApp.Start<Startup>(url))
                {
                    esgDS.LoadDataFromDB().Wait();
                    SubscribeToTopicEvents();
                    Console.WriteLine("Started on: " + url);
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                Log.Error(ex, "");
            }
        }

        public static void SubscribeToTopicEvents()
        {
            var settings = new ActiveMQAppSettings(ConfigurationManager.Instance.AppSettings, ConfigurationManager.Instance.ConnectionStrings);
            var factory = new ActiveMQFactory(settings);
            consumer = factory.CreateConsumer();
            consumer.MessageReceived += OnMessageReceivedHandler;
        }

        private static void OnMessageReceivedHandler(ComputationSetMessage message)
        {
            try
            {
                esgDS.SwithchSet(message.DeletableSetIds, message.ActiveSetId).Wait();
            }
            catch (AggregateException ex)
            {
                Log.Error(ex, "");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "");
            }
        }
    }
}